package com.hqs.listener.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.hqs.common.utils.SharedPreferenceUtil;
import com.hqs.listener.R;
import com.hqs.listener.activity.MainActivity;
import com.hqs.listener.view.QTextView;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by super on 2017/11/13.
 */

public class PlayerFragment extends BaseFragment {


    @BindView(R.id.image)
    ImageView imageView;

    @BindView(R.id.imgPre)
    Button imgPre;

    @BindView(R.id.imgPlay)
    Button imgPlay;

    @BindView(R.id.imgNext)
    Button imgNext;

    @BindView(R.id.progress)
    ProgressBar progressBar;

    @BindView(R.id.tvTitle)
    QTextView tvTitle;

    MusicReceiver musicReceiver;
    UpdateProgressThread updateProgressThread;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_player, null);

        ButterKnife.bind(this, view);
        setup();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (service != null) {
            tvTitle.setText(service.getCurrentFileName());
        }
    }

    @Override
    public void didSetService() {
        restore();
    }

    private void setup() {

        int normal = getResources().getColor(R.color.colorPrimary);
        int focused = Color.argb(255, 224, 178, 103);
        int pressed = focused;

        int[] colors = new int[]{pressed, focused, normal, focused, normal, normal};
        int[][] states = new int[6][];
        states[0] = new int[]{android.R.attr.state_pressed, android.R.attr.state_enabled};
        states[1] = new int[]{android.R.attr.state_enabled, android.R.attr.state_focused};
        states[2] = new int[]{android.R.attr.state_enabled};
        states[3] = new int[]{android.R.attr.state_focused};
        states[4] = new int[]{android.R.attr.state_window_focused};
        states[5] = new int[]{};
        ColorStateList colorList = new ColorStateList(states, colors);

        imgPre.setBackgroundTintList(colorList);
        imgNext.setBackgroundTintList(colorList);
        imgPlay.setBackgroundTintList(colorList);

        imgPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (!service.isPlaying()) {
                    playMusic();
                } else {
                    pauseMusic();
                }
            }
        });
        imgPre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                service.playPreMusic();
            }
        });
        imgNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                service.playNextMusic();
            }
        });

        updatePlayButton();

        musicReceiver = new MusicReceiver();
        IntentFilter filter = new IntentFilter("music_action");
        getActivity().registerReceiver(musicReceiver, filter);
    }

    private void updatePlayButton() {

        boolean isPlaying = SharedPreferenceUtil.get("isPlaying", false);
        if (isPlaying) {
            imgPlay.setBackgroundResource(R.mipmap.pause);
        } else {
            imgPlay.setBackgroundResource(R.mipmap.play);
        }
    }

    private void restore() {
        tvTitle.post(new Runnable() {
            @Override
            public void run() {
                tvTitle.setText(service.getCurrentFileName());

                if (!service.isPlaying()) {
                    imgPlay.setBackgroundResource(R.mipmap.play);
                    progressBar.setMax(SharedPreferenceUtil.get("currentDuration", 100));
                    progressBar.setProgress(SharedPreferenceUtil.get("currentPosition", 0));

                    if (service.getMediaPlayer() != null) {
                        service.getMediaPlayer().seekTo(progressBar.getProgress());
                        service.getMediaPlayer().setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                            @Override
                            public void onSeekComplete(MediaPlayer mediaPlayer) {
                                if (updateProgressThread != null){
                                    updateProgressThread.isRunning = false;
                                    updateProgressThread = null;
                                }
                                updateProgressThread = new UpdateProgressThread();
                                updateProgressThread.start();
                            }
                        });
                    }
                } else {
                    imgPlay.setBackgroundResource(R.mipmap.pause);
                    if (updateProgressThread != null){
                        updateProgressThread.isRunning = false;
                        updateProgressThread = null;
                    }
                    updateProgressThread = new UpdateProgressThread();
                    updateProgressThread.start();
                }
            }
        });
    }


    private void playMusic() {
        if (service == null) {
            return;
        }
        service.start();
    }

    private void pauseMusic() {
        if (service == null) {
            return;
        }
        service.pause();
    }

    class UpdateProgressThread extends Thread {

        boolean isRunning = true;
        @Override
        public void run() {

            int cur;
            int total;
            while (isRunning) {
                if (MainActivity.instance.viewPager.getCurrentItem() == 1) {
                    if (service.isPlaying()) {
                        total = service.getMediaPlayer().getDuration();
                        cur = service.getMediaPlayer().getCurrentPosition();

                        progressBar.setMax(total);
                        final int p = cur;
                        progressBar.post(new Runnable() {
                            @Override
                            public void run() {
                                progressBar.setProgress(p);
                            }
                        });
                    }
                }
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getActivity().unregisterReceiver(musicReceiver);
        if (updateProgressThread != null){
            updateProgressThread.isRunning = false;
            updateProgressThread = null;
        }
    }

    public class MusicReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String msg = intent.getExtras().getString("msg");
            if ("start".equals(msg)) {
                imgPlay.setBackgroundResource(R.mipmap.pause);
            } else if ("pause".equals(msg)) {
                imgPlay.setBackgroundResource(R.mipmap.play);
            } else if (msg.indexOf("file: ") == 0) {
                tvTitle.setText(msg.substring(6));
            }
        }
    }

}
